package tec.code;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {
	public static List<Character> loadChar(String file, String charset) throws IOException {
		List<Character> content = new ArrayList<Character>();
		BufferedReader in = new BufferedReader(
			new InputStreamReader(new FileInputStream(file), charset)
		);
		int c;
		while((c = in.read()) != -1) content.add((char) c);
		in.close();
		return(content);
	}
	
	public static void save(List<Character> chars, String file, String encode) throws IOException {
		Writer out = getFileWriter(file, encode);
		
		for(char c : chars) out.write(c);
		out.flush();
		out.close();
	}
	
	public static void save(String content, String file, String encode) throws IOException {
		Writer out = getFileWriter(file, encode);
			out.write(content);
			out.flush();
			out.close();		
	}

	public static List<String> readTxtFile(String file, String charset) throws IOException {
		List<String> lines = new ArrayList<String>();
		BufferedReader in = new BufferedReader(
			new InputStreamReader(new FileInputStream(file), charset)
		);
		
		String line;
		while((line = in.readLine()) != null) lines.add(line);
		in.close();
		
		return(lines);
	}	
	
	private static Writer getFileWriter(String file, String encode) throws IOException {
		BufferedWriter out = new BufferedWriter(
				new OutputStreamWriter(new FileOutputStream(file), encode)
		);
		return(out);
	}	
}
